﻿using BarrageGameAssistant.Core.Model;
using BarrageGameAssistant.Core.Model.Base;
using KMSimulator.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace BarrageGameAssistant.Core.Configs
{
    public class GameProject : ConfigBase
    {
        /// <summary>
        /// 当前游戏句柄
        /// </summary>
        [JsonIgnore]
        public nint Handle { get; set; }

        /// <summary>
        /// 当前游戏进程ID
        /// </summary>
        [JsonIgnore]
        public nint GameProcessId { get; set; }

        /// <summary>
        /// 游戏ID
        /// </summary>
        public string Id { get; set; } = Guid.NewGuid().ToString();

        /// <summary>
        /// 游戏平台
        /// </summary>
        public int Platform { get; set; } = 0;

        /// <summary>
        /// 游戏名称
        /// </summary>
        public string Name { get; set; } = string.Empty;

        /// <summary>
        /// 游戏进程
        /// </summary>
        public string ProcessName { get; set; } = string.Empty;

        /// <summary>
        /// 游戏类型
        /// </summary>
        public int GameCategory { get; set; }

        #region 窗体设置

        /// <summary>
        /// 游戏界面设置为最顶层
        /// </summary>
        public bool AutoGameTop { get; set; } = true;

        /// <summary>
        /// 自动设置游戏到最前端
        /// </summary>
        public bool AutoGameForeground { get; set; } = true;

        /// <summary>
        /// 自动聚焦游戏窗体
        /// </summary>
        public bool AutoGameFocus { get; set; } = true;

        /// <summary>
        /// 自动游戏窗体为正常化
        /// </summary>
        public bool AutoGameWindowNormal { get; set; } = true;

        /// <summary>
        /// 自动改变游戏窗体坐标
        /// </summary>
        public bool AutoChangeGameLocation { get; set; } = true;

        /// <summary>
        /// 自动改变游戏窗体大小
        /// </summary>
        public bool AutoChangeGameSize { get; set; } = false;

        /// <summary>
        /// 是否自动缩略画面
        /// </summary>
        public bool AutoThumbnail { get; set; } = true;

        /// <summary>
        /// 窗体宽度修正值
        /// </summary>
        public int WindowSetFixWidth { get; set; } = 0; //16;

        /// <summary>
        /// 窗体高度修正值
        /// </summary>
        public int WindowSetFixHeigh { get; set; } = 0; //8;

        /// <summary>
        /// 窗体x偏移量
        /// </summary>
        public int WindowSetOffsetX { get; set; } = 0; //-8;

        /// <summary>
        /// 窗体x偏移量
        /// </summary>
        public int WindowSetOffsetY { get; set; } = 0;

        /// <summary>
        /// 游戏窗体设置的大小和位置
        /// </summary>
        public Point WindowsSetLocation { get; set; } = new Point(50, 20);

        /// <summary>
        /// 是否裁剪图片
        /// </summary>
        public bool IsCropImage { get; set; }

        /// <summary>
        /// 裁剪图片尺寸
        /// </summary>
        public Size CropImageSize { get; set; } = Size.Empty;

        /// <summary>
        /// 裁剪图片起始位置
        /// </summary>
        public Point CropImageLocation { get; set; } = Point.Empty;
        #endregion

        public string DefaultModeSelectionId { get; set; } = "68a36eeb-94c5-47f2-bfd8-8a2b59b800b3";

        /// <summary>
        /// 游戏模式选项
        /// </summary>
        public List<GameModeSelection> ModeSelections { get; set; }

        /// <summary>
        /// 场景集合
        /// </summary>
        public List<Scene> Scenes { get; set; }

        /// <summary>
        /// 游戏介绍话术
        /// </summary>
        public List<LanguageScript> IntroScripts { get; set; }

        /// <summary>
        /// 邀请话术
        /// </summary>
        public List<LanguageScript> InviteScripts { get; set; }

        /// <summary>
        /// 游戏过程处理条件
        /// </summary>
        public List<GameProcessCondition> GameProcessConditions { get; set; }

        public GameProject()
        {
            Scenes = [];
            IntroScripts = [];
            InviteScripts = [];
            GameProcessConditions = [];
            ModeSelections = [];
        }

        /// <summary>
        /// 初始化游戏项目
        /// </summary>
        /// <param name="gamesDir">游戏集合目录</param>
        public void InitGameProject(string gamesDir)
        {
            if (string.IsNullOrEmpty(Name))
                return;

            if (!Directory.Exists(gamesDir))
                return;

            var gameDir = Path.Combine(gamesDir, $"{GetPlatformName()}{Name}");
            if (!Directory.Exists(gameDir))
                Directory.CreateDirectory(gameDir);
            else
            {
                Directory.Delete(gameDir, true);
                Directory.CreateDirectory(gameDir);
            }

            var dataDir = Path.Combine(gameDir, "Data");
            if (!Directory.Exists(dataDir))
                Directory.CreateDirectory(dataDir);
            var sceneDir = Path.Combine(gameDir, "Scenes");
            if (!Directory.Exists(sceneDir))
                Directory.CreateDirectory(sceneDir);

            if (ModeSelections.Count == 0)
            {
                GameModeSelection defMode = new()
                {
                    Id = "68a36eeb-94c5-47f2-bfd8-8a2b59b800b3",
                    Name = "默认模式"
                };
                ModeSelections.Add(defMode);
            }

            var prjFile = Path.Combine(gameDir, "project.json");
            Save(prjFile);
        }

        #region 载入和保存
        public static GameProject? Load(string filePath, bool nullCreate = false)
        {
            List<JsonConverter> JsonConverters =
                    [
                        new KMActionConverter()
                    ];

            var result = Load<GameProject>(filePath, JsonConverters);
            if (nullCreate && result == null)
            {
                result = new GameProject();
                result.Save(filePath);
            }
            return result;
        }
        #endregion

        public string GetPlatformName()
        {
            if (this.Platform == 0)
                return "抖音";
            else if (this.Platform == 1)
                return "快手";
            else return "未知";
        }
    }

    public class KMActionConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(KMActionBase).IsAssignableFrom(objectType);
        }

        public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
        {
            JObject jsonObject = JObject.Load(reader);

            //// 根据 JSON 中的 "type" 属性创建相应的对象
            var eType = jsonObject?["ActionType"]?.ToObject<KMActionType>();

            if (eType == KMActionType.Keyboard)
            {
                return jsonObject?.ToObject<KeyboardAction>();
            }
            else if (eType == KMActionType.InputText)
            {
                return jsonObject?.ToObject<InputTextAction>();
            }
            else if (eType == KMActionType.MouseClick)
            {
                return jsonObject?.ToObject<MouseClickAction>();
            }
            else if (eType == KMActionType.MouseDoubleClick)
            {
                return jsonObject?.ToObject<MouseDoubleClickAction>();
            }
            else if (eType == KMActionType.MouseMove)
            {
                return jsonObject?.ToObject<MouseMoveAction>();
            }
            else if (eType == KMActionType.MouseDrag)
            {
                return jsonObject?.ToObject<MouseDragAction>();
            }
            else if (eType == KMActionType.MouseWheel)
            {
                return jsonObject?.ToObject<MouseWheelAction>();
            }
            return null;
        }

        public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
}
